// Copyright (C) 2025 Focus Media Holding Ltd. All Rights Reserved.

package cn.pacerx.running.wx.service;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.pacerx.running.core.util.IpUtil;
import cn.pacerx.running.core.util.ResponseUtil;
import cn.pacerx.running.db.domain.User;
import cn.pacerx.running.db.service.UserService;
import cn.pacerx.running.wx.dto.UserDto;
import cn.pacerx.running.wx.dto.WechatLoginDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

/**
 * AuthService
 *
 * @author zhanglingwei@focusmedia.cn
 * @since 2025-06-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {
    private final WxMaService wxService;
    private final UserService userService;
    private final EventService eventService;

    public Object loginByWechat(WechatLoginDto wechatLoginDto, HttpServletRequest request) {
        String sessionKey = null;
        String openId = null;
        try {
            WxMaJscode2SessionResult result = this.wxService.getUserService().getSessionInfo(wechatLoginDto.getCode());
            sessionKey = result.getSessionKey();
            openId = result.getOpenid();
        } catch (Exception e) {
            log.error("fail to get session info", e);
            return ResponseUtil.serious();
        }

        if (sessionKey == null || openId == null) {
            return ResponseUtil.fail();
        }

        User user = userService.queryByOid(openId);
        if (user == null) {
            user = new User();
            user.setUsername(openId);
            user.setPassword(openId);
            user.setWeixinOpenid(openId);
            user.setNickname("微信用户");
            user.setGender((byte) 0);
            user.setUserLevel((byte) 0);
            user.setStatus((byte) 0);
            user.setLastLoginTime(LocalDateTime.now());
            user.setLastLoginIp(IpUtil.getIpAddr(request));
            user.setSessionKey(sessionKey);

            userService.add(user);

            // 新用户静默注册事件示例
            eventService.buildDefaultEvent((long) user.getId());
        } else {
            user.setLastLoginTime(LocalDateTime.now());
            user.setLastLoginIp(IpUtil.getIpAddr(request));
            user.setSessionKey(sessionKey);
            if (userService.updateById(user) == 0) {
                return ResponseUtil.updatedDataFailed();
            }
        }

        UserDto userDto = new UserDto();
        userDto.setNickName(user.getNickname());
        userDto.setGender(user.getGender());
        userDto.setAvatarUrl(user.getAvatar());
        // token
        String token = UserTokenManager.generateToken(user.getId());

        Map<Object, Object> result = new HashMap<>();
        result.put("token", token);
        result.put("userInfo", userDto);
        return ResponseUtil.ok(result);
    }
}
